package pers.cz.logtail;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * @program: JefLogTail
 * @description: 服务注册
 * @author: Cheng Zhi
 * @create: 2023-10-04 20:09
 **/
public class ServiceRegistByZk {


    private static final String SERVICE_REGISTRY_ROOT = "/services";

    private static final int SESSION_TIMEOUT = 5000;

    private ZooKeeper zooKeeper;

    public ServiceRegistByZk(String zooKeeperAddress) throws IOException {
        this.zooKeeper = new ZooKeeper(zooKeeperAddress, SESSION_TIMEOUT, null);
    }

    /**
     * 注册服务
     *
     * @param serviceName    服务名称
     * @param serviceAddress 服务地址
     * @throws KeeperException
     * @throws InterruptedException
     */
    public void registryService(String serviceName, String serviceAddress) throws KeeperException, InterruptedException {
        String servicePath = SERVICE_REGISTRY_ROOT + "/" + serviceName;

        // 如果根节点不存在就创建
        if (zooKeeper.exists(SERVICE_REGISTRY_ROOT, false) == null) {
            zooKeeper.create(SERVICE_REGISTRY_ROOT, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }

        String serviceNodePath = zooKeeper.create(servicePath, serviceAddress.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("注册成功;serviceNodePath:" + serviceNodePath);
    }

    public void close() throws InterruptedException {
        zooKeeper.close();
    }

}
